import sys
import pygame
from matplotlib.style.core import available
from pygame.examples import aliens

import ship
from alien import Alien
from bullet import Bullet
from time import sleep


def start_game(ai_settings, screen, stats, sb, ship, aliens, bullets):
    # 隐藏光标
    pygame.mouse.set_visible(False)
    stats.ship_left -= 1
    # 重置游戏统计信息
    stats.reset_stats()
    stats.game_active = True
    # 重置记分牌和图像
    # 读取最历史高分
    high_score = read_high_score(ai_settings)
    if high_score:
        stats.high_score = int(read_high_score(ai_settings))
    else:
        stats.high_score = 0
    sb.prep_images()
    # 清空外星人列表 和子弹列表
    aliens.empty()
    bullets.empty()

    # 创建一群新外星人并让飞船居中
    create_fleet(ai_settings, screen, ship, aliens)
    ship.center_ship()
    
    # 播放背景音乐
    if not pygame.mixer.music.get_busy():
        pygame.mixer.music.play(-1)


def check_play_button(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, mouse_x, mouse_y):
    """玩家点击 ‘开始’ 按钮时开始新游戏"""
    button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)
    if button_clicked and not stats.game_active:
        # 重置游戏设置
        ai_settings.initialize_dynamicc_setting()
        # 开始游戏
        start_game(ai_settings, screen, stats, sb, ship, aliens, bullets)


def check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, sounds):
    """响应按键和鼠标事件"""
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            write_high_score(ai_settings,stats)
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event, ai_settings, screen, ship, bullets, stats, sb, aliens, sounds)
        elif event.type == pygame.KEYUP:
            check_keyup_events(event, ship)
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = pygame.mouse.get_pos()
            check_play_button(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, mouse_x, mouse_y)

def check_keydown_events(event, ai_settings, screen, ship, bullets, stats, sb, aliens, sounds):
    # key_name = pygame.key.name(event.key)
    # print("KEYDOWN 事件，按键值 event.key =" + str(event.key) + ", 对应的按键名称: " + key_name)
    # print(event.key, flush=True)  # 强制刷新输出
    """响应按键"""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = True
    elif event.key == pygame.K_LEFT:
        ship.moving_left = True
    elif event.key == pygame.K_SPACE:
        # ai_settings.fire_flag = True
        # # 创建一颗子弹，并将其加入到编组bulets中
        fire_bullet(ai_settings, screen, ship, bullets, sounds)
    elif event.key == pygame.K_q or event.key == pygame.K_ESCAPE:
        write_high_score(ai_settings, stats)
        pygame.quit()
        sys.exit()
    elif event.key == pygame.K_p:
        # 重置游戏设置
        ai_settings.initialize_dynamicc_setting()
        start_game(ai_settings, screen, stats, sb, ship, aliens, bullets)
    elif event.key == pygame.K_EQUALS or event.key == pygame.K_PLUS:
        # 增加音量 (+ 键)
        adjust_volume(ai_settings, sounds, increase=True)
    elif event.key == pygame.K_MINUS:
        # 减小音量 (- 键)
        adjust_volume(ai_settings, sounds, increase=False)
    elif event.key == pygame.K_m:
        # 切换静音 (M 键)
        toggle_mute()


def check_keyup_events(event, ship):
    """响应松开"""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    elif event.key == pygame.K_LEFT:
        ship.moving_left = False


def fire_bullet(ai_settings, screen, ship, bullets, sounds):
    """如果没有达到限制，就发一颗子弹"""
    if len(bullets) < ai_settings.bullet_allowed:
        new_bullet = Bullet(ai_settings, screen, ship)
        bullets.add(new_bullet)
        # 播放发射音效
        sounds['ship_shot'].play()


def update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets):
    """更新子弹位置并删除已消失子弹"""
    bullets.update()
    for bullet in bullets.copy():
        if bullet.rect.bottom <= 0:
            bullets.remove(bullet)
    check_bullet_alien_collisions(ai_settings, screen, stats, sb, ship, aliens, bullets)


def check_bullet_alien_collisions(ai_settings, screen, stats, sb, ship, aliens, bullets):
    """响应外星人和子弹发生碰撞"""
    # 检查是否有子弹击中了外星人
    # 如果这样就，删除对应子弹和外星人
    collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)
    if collisions:
        for aliens in collisions.values():
            stats.score += ai_settings.alien_points * len(aliens)
            sb.pre_score()
        check_high_score(stats, sb)

    if len(aliens) == 0:
        # 开始新等级
        start_new_level(ai_settings, screen, stats, sb, ship, aliens, bullets)

def start_new_level(ai_settings, screen, stats, sb, ship, aliens, bullets):
    # 删除现有子弹,加快游戏节奏，并创建一群外星人
    bullets.empty()
    ai_settings.increase_speed()
    stats.level += 1
    sb.pre_level()
    create_fleet(ai_settings, screen, ship, aliens)

def update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button):
    # 每次循环时都重绘屏幕
    screen.fill(ai_settings.bg_color)
    for bullet in bullets.sprites():
        bullet.draw_bullet()
    ship.blitme()
    aliens.draw(screen)
    sb.show_score()
    # 如果游戏牌非活跃状态，就绘制play按钮
    if not stats.game_active:
        play_button.draw_button()
    # 让最近绘制的屏幕可见
    pygame.display.flip()


# 外星人相关函数
def create_fleet(ai_settings, screen, ship, aliens):
    """创建外星人群"""
    # 创建一个外星人，并计算一行可容纳多少外星人
    # 外星人间距为外星人宽度
    alien = Alien(ai_settings, screen)
    number_aliens_x = get_number_aliens_x(ai_settings, alien.rect.width)
    number_rows = get_nuber_rows(ai_settings, ship.rect.height, alien.rect.height)

    # 创建第一行外星人
    for row_number in range(number_rows):
        for alien_index in range(number_aliens_x):
            create_alien(ai_settings, screen, aliens, alien_index, row_number)


def get_number_aliens_x(ai_settings, alien_width):
    available_space_x = ai_settings.screen_width - 2 * alien_width
    number_aliens_x = int(available_space_x / (2 * alien_width))
    return number_aliens_x


def create_alien(ai_settings, screen, aliens, alien_index, row_number):
    # 创建一个外星人并将其加入当前行
    alien = Alien(ai_settings, screen)
    alien_width = alien.rect.width
    alien.x = alien_width + 2 * alien_width * alien_index
    alien.rect.x = alien.x
    alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
    aliens.add(alien)


def get_nuber_rows(ai_settings, ship_height, alien_height):
    """计算屏幕可容纳多少行外星人"""
    available_space_y = ai_settings.screen_height - 3 * alien_height - ship_height
    number_rows = int(available_space_y / (2 * alien_height))
    return number_rows


def check_fleet_edges(ai_setting, aliens):
    """有外星人到达边缘时采取相应的措施"""
    for alien in aliens.sprites():
        if alien.check_edges():
            change_fleet_direction(ai_setting, aliens)
            break


def change_fleet_direction(ai_setting, aliens):
    for alien in aliens.sprites():
        alien.rect.y += ai_setting.fleet_drop_speed
    ai_setting.fleet_direction *= -1


def update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets, sounds):
    """检查是否有外星人位于屏幕边缘，并更新整群星外星人位置 """
    check_fleet_edges(ai_settings, aliens)
    aliens.update()
    # 检测外星人和飞船之间的碰撞
    if pygame.sprite.spritecollideany(ship, aliens):
        ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets, sounds)

    # 检查是否有外星人到达屏幕底端
    check_aliens_bottom(ai_settings, stats, screen, sb, ship, aliens, bullets, sounds)


# 外星人撞飞船时
# 1， 余下飞船数-1
# 2， 创建一群新的外星人
# 3， 飞船重置到屏幕底端中央
# 4， 让游戏暂停一会
def ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets, sounds):
    # 播放爆炸音效
    sounds['explosion'].play()
    
    if stats.ship_left > 0:
        # ships_left-1
        stats.ship_left -= 1
        # 更新记分牌
        sb.pre_ships()

        # 清空外星人和子弹列表
        aliens.empty()
        bullets.empty()

        # 创建一群新外星人
        create_fleet(ai_settings, screen, ship, aliens)
        ship.center_ship()

        # 暂停
        sleep(1)
    else:
        stats.game_active = False
        # 光标可见
        pygame.mouse.set_visible(True)
        # 停止背景音乐
        pygame.mixer.music.pause()


def check_aliens_bottom(ai_settings, stats, screen, sb, ship, aliens, bullets, sounds):
    """检查是否有外星人到达了屏幕底端"""
    screen_rect = screen.get_rect()
    for alien in aliens.sprites():
        if alien.rect.bottom >= screen_rect.bottom:
            # 像飞船被撞到一样处理
            ship_hit(ai_settings, stats, screen, sb, ship, aliens, bullets, sounds)
            break


def check_high_score(stats, sb):
    """检查是否诞生了新的最高得分"""
    if stats.score > stats.high_score:
        stats.high_score = stats.score
        sb.pre_high_score()

def write_high_score(ai_settings, stats):
    high_score = int(round(stats.high_score, -1))
    with open(ai_settings.high_score_file_path, "w") as file:
        file.write(str(high_score))

def read_high_score(ai_settings):
    with open(ai_settings.high_score_file_path) as file:
        high_score = file.read()
    return high_score

def adjust_volume(ai_settings, sounds, increase=True):
    """调整音量大小"""
    if increase:
        # 增加音量
        ai_settings.music_volume = min(1.0, ai_settings.music_volume + ai_settings.volume_step)
        ai_settings.sound_volume = min(1.0, ai_settings.sound_volume + ai_settings.volume_step)
        print(f"音量增加到: 音乐 {ai_settings.music_volume:.1f}, 音效 {ai_settings.sound_volume:.1f}")
    else:
        # 减小音量
        ai_settings.music_volume = max(0.0, ai_settings.music_volume - ai_settings.volume_step)
        ai_settings.sound_volume = max(0.0, ai_settings.sound_volume - ai_settings.volume_step)
        print(f"音量减小到: 音乐 {ai_settings.music_volume:.1f}, 音效 {ai_settings.sound_volume:.1f}")
    
    # 更新背景音乐音量
    pygame.mixer.music.set_volume(ai_settings.music_volume)
    # 更新所有音效的音量
    for sound in sounds.values():
        sound.set_volume(ai_settings.sound_volume)

def toggle_mute():
    """切换静音状态"""
    current_volume = pygame.mixer.music.get_volume()
    if current_volume > 0:
        pygame.mixer.music.set_volume(0)
        print("静音：开启")
    else:
        pygame.mixer.music.set_volume(0.3)
        print("静音：关闭")
